home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / common / proxysockets.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  17KB  |  484 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from util import GetProxyInfo
  5. from AsyncSocket import AsyncSocket as asocket
  6. import socks
  7. from socket import _socket as socket
  8. from functools import wraps
  9. import sys
  10. import logging
  11. log = logging.getLogger('proxysockets')
  12.  
  13. class ProxyType:
  14.     SOCKS4 = socks.PROXY_TYPE_SOCKS4
  15.     SOCKS5 = socks.PROXY_TYPE_SOCKS5
  16.     HTTP = socks.PROXY_TYPE_HTTP
  17.     HTTPS = socks.PROXY_TYPE_HTTPS
  18.  
  19.  
  20. class ProxySocket(asocket):
  21.     
  22.     def __init__(self, proxy, conn, post, callback):
  23.         asocket.__init__(self, conn)
  24.         self.callback = callback
  25.         self.post_negotiate = post
  26.         self._negotiating = False
  27.         if proxy is None:
  28.             proxy = { }
  29.         
  30.         self._proxyinfo = proxy.copy()
  31.         self.mid = (self._proxyinfo.get('addr', ''), self._proxyinfo.get('port', 0))
  32.         self.end = ('', 0)
  33.  
  34.     
  35.     def connect(self, end):
  36.         self.end = end
  37.         self._pconnect()
  38.  
  39.     
  40.     def _pconnect(self):
  41.         asocket.connect(self, self.mid)
  42.  
  43.     
  44.     def handle_close(self):
  45.         log.info('ProxySocket.handle_close - calling callback.error')
  46.         self.close()
  47.         asocket.handle_close(self)
  48.  
  49.     
  50.     def close(self):
  51.         if getattr(self, 'socket', None) is not None:
  52.             asocket.close(self)
  53.         
  54.         if self.callback is not None:
  55.             self.callback = None
  56.             cb = self.callback
  57.             cb.error()
  58.         
  59.  
  60.     
  61.     def handle_connect(self):
  62.         if not self._negotiating:
  63.             log.info('ProxySocket connected. starting negotiation... ')
  64.             self._negotiating = True
  65.             self._pnegotiate()
  66.         
  67.  
  68.     
  69.     def _pnegotiate(self):
  70.         negs = {
  71.             ProxyType.HTTP: self._negotiatehttp,
  72.             ProxyType.HTTPS: self._negotiatehttps,
  73.             ProxyType.SOCKS4: self._negotiatesocks4,
  74.             ProxyType.SOCKS5: self._negotiatesocks5 }
  75.         neg = negs.get(self._proxyinfo.get('proxytype', None), self._negotiation_done)
  76.         neg()
  77.  
  78.     
  79.     def _negotiatehttp(self):
  80.         
  81.         try:
  82.             endhost = self._endhost_resolved = socket.gethostbyname(self.end[0])
  83.         except socket.gaierror:
  84.             self._endhost_resolved = None
  85.             endhost = self.end[0]
  86.  
  87.         endport = self.end[1]
  88.         authstr = self._httpauthstring()
  89.         http_connect = 'CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n%s\r\n' % (endhost, endport, self.end[0], authstr)
  90.         None(log.info, 'ProxySocket._negotiatehttp: sending proxy CONNECT%s. %r:%r' if authstr else '', self, (endhost, endport))
  91.         self.push(http_connect)
  92.         self.push_handler(self._httpfinish)
  93.         self.set_terminator('\r\n\r\n')
  94.  
  95.     
  96.     def _httpauthstring(self):
  97.         username = self._proxyinfo.get('username', None)
  98.         password = self._proxyinfo.get('password', None)
  99.         if all((username, password)):
  100.             raw = '%s:%s' % (username, password)
  101.             auth = 'Basic %s' % ''.join(raw.encode('base-64').strip().split())
  102.             return 'Proxy-Authorization: %s\r\n' % auth
  103.         else:
  104.             return ''
  105.  
  106.     
  107.     def _httpfinish(self, data):
  108.         self.pop_handler()
  109.         statusline = data.splitlines()[0].split(' ', 2)
  110.         if statusline[0] not in ('HTTP/1.0', 'HTTP/1.1'):
  111.             log.info('ProxySocket._httpfinish: Bad data from server, disconnecting: (%r)', data)
  112.             return self.close()
  113.         
  114.         
  115.         try:
  116.             statuscode = int(statusline[1])
  117.         except ValueError:
  118.             log.info('ProxySocket._httpfinish: Got some bad data from the server, disconnecting: %r (%r)', statusline, data)
  119.             return self.close()
  120.  
  121.         if statuscode != 200:
  122.             log.info('ProxySocket._httpfinish: got HTTPError code %r, disconnecting (%r)', statuscode, data)
  123.             return self.close()
  124.         
  125.         log.info('ProxySocket._httpfinish: success %r', self)
  126.         self._ProxySocket__proxysockname = ('0.0.0.0', 0)
  127.         if not self._endhost_resolved:
  128.             pass
  129.         self._ProxySocket__proxypeername = (self.end[0], self.end[1])
  130.         self._negotiation_done()
  131.  
  132.     
  133.     def _negotiation_done(self):
  134.         log.info('proxy negotiation complete')
  135.         self._proxy_setup = True
  136.         self.del_channel()
  137.         self.finish(self.socket, 'handle_connect')
  138.         if self.callback is not None:
  139.             self.callback.success()
  140.         
  141.         self.callback = None
  142.         self.socket = None
  143.  
  144.     
  145.     def finish(self, sck, handler_name):
  146.         sck = self.post_negotiate(sck)
  147.         sck.connected = True
  148.         sck._proxy_setup = True
  149.         self.collect_incoming_data = sck.collect_incoming_data
  150.         getattr(sck, handler_name)()
  151.  
  152.     
  153.     def _negotiatehttps(self):
  154.         raise NotImplementedError
  155.  
  156.     
  157.     def _negotiatesocks4(self):
  158.         pack = pack
  159.         import struct
  160.         destaddr = self.end[0]
  161.         destport = self.end[1]
  162.         rresolve = False
  163.         
  164.         def zstring(s):
  165.             return s + '\x00'
  166.  
  167.         
  168.         try:
  169.             ipaddr = socket.inet_aton(destaddr)
  170.         except socket.error:
  171.             
  172.             try:
  173.                 ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  174.             except socket.error:
  175.                 str
  176.                 ipaddr = pack('!I', 1)
  177.                 rresolve = True
  178.             except:
  179.                 None<EXCEPTION MATCH>socket.error
  180.             
  181.  
  182.             None<EXCEPTION MATCH>socket.error
  183.  
  184.         req = pack('!BBH', 4, 1, destport) + ipaddr
  185.         username = self._proxyinfo.get('username', '')
  186.         req += zstring(username)
  187.         if rresolve:
  188.             req += zstring(destaddr)
  189.         
  190.         log.info('ProxySocket._negotiatesocks4: sending request')
  191.         self.push(req)
  192.         self.push_handler(self._socks4finish)
  193.         self.set_terminator(8)
  194.         if rresolve:
  195.             self._ProxySocket__proxypeername = (socket.inet_ntoa(ipaddr), destport)
  196.         else:
  197.             self._ProxySocket__proxypeername = (destaddr, destport)
  198.  
  199.     
  200.     def _socks4finish(self, data):
  201.         unpack = unpack
  202.         import struct
  203.         self.pop_handler()
  204.         log.info('ProxySocket._negotiatesocks4: received response')
  205.         
  206.         try:
  207.             (null, returncode, port, ip) = unpack('!BBH4s', data)
  208.         except Exception:
  209.             e = None
  210.             log.info('ProxySocket._negotiatesocks4: bad data received from server. original exception is: %r', e)
  211.             return self.close()
  212.  
  213.         ip = socket.inet_ntoa(ip)
  214.         if null != 0:
  215.             log.info('ProxySocket._negotiatesocks4: Bad data from server- expected null byte, got %r', null)
  216.             return self.close()
  217.         
  218.         if returncode != 90:
  219.             log.info('ProxySocket._negotiatesocks4: received error code %r', returncode)
  220.             return self.close()
  221.         
  222.         log.info('ProxySocket._negotiatesocks4: success')
  223.         self._ProxySocket__proxysockname = (ip, port)
  224.         self._negotiation_done()
  225.  
  226.     
  227.     def _negotiatesocks5_gen(self):
  228.         pack = pack
  229.         unpack = unpack
  230.         import struct
  231.         Storage = Storage
  232.         import util
  233.         (destaddr, destport) = self.end
  234.         uname = self._proxyinfo.get('username', '')
  235.         password = self._proxyinfo.get('password', '')
  236.         this = Storage()
  237.         this.errors = False
  238.         this.authtype = 0
  239.         this.incoming_host_type = 0
  240.         
  241.         def pstring(s):
  242.             return chr(len(s)) + s
  243.  
  244.         
  245.         def single_use_handler(f):
  246.             
  247.             def wrapper(data):
  248.                 self.pop_handler()
  249.                 return f(data)
  250.  
  251.             wrapper = (None, wraps(f))(wrapper)
  252.             return wrapper
  253.  
  254.         
  255.         def if_errors_close(f):
  256.             
  257.             def wrapper(*a, **k):
  258.                 ok = not (this.errors)
  259.                 if ok:
  260.                     
  261.                     try:
  262.                         return f(*a, **k)
  263.                     except Exception:
  264.                         e = None
  265.                         log.info('ProxySocket._negotiatesocks5: there was an error calling %r(*%r, **%r). the exception was: %r', f, a, k, e)
  266.                         this.errors = True
  267.                         self.close()
  268.                         return ('', None)
  269.                     except:
  270.                         None<EXCEPTION MATCH>Exception
  271.                     
  272.  
  273.                 None<EXCEPTION MATCH>Exception
  274.                 log.info('ProxySocket._negotiatesocks5: Previous errors prevented %r(*%r, **%r) from happening', f, a, k)
  275.                 return ('', None)
  276.  
  277.             return wrapper
  278.  
  279.         sender = if_errors_close
  280.         
  281.         def recver(f):
  282.             return if_errors_close(single_use_handler(f))
  283.  
  284.         
  285.         def _sendauthtype():
  286.             if uname and password:
  287.                 data = pack('!BBBB', 5, 2, 0, 2)
  288.             else:
  289.                 data = pack('!BBB', 5, 1, 0)
  290.             return (data, 2)
  291.  
  292.         _sendauthtype = (None, (None, (None, (None,))), sender)(_sendauthtype)
  293.         
  294.         def _recvauthtype(data):
  295.             (status, authmethod) = unpack('!BB', data)
  296.             if status != 5:
  297.                 raise Exception('Bad data was received from the proxy server: %r', data)
  298.             
  299.             if authmethod in (0, 2):
  300.                 this.authtype = authmethod
  301.             elif authmethod == 255:
  302.                 this.authtype = None
  303.                 raise Exception('All auth methods were rejected')
  304.             
  305.  
  306.         _recvauthtype = (None, recver)(_recvauthtype)
  307.         
  308.         def _sendauth():
  309.             return (chr(1) + pstring(uname) + pstring(password), 2)
  310.  
  311.         _sendauth = (None, None, sender)(_sendauth)
  312.         
  313.         def _recvauth(data):
  314.             (code, status) = map(ord, data)
  315.             if code != 1:
  316.                 raise Exception('Was expecting 1, got %r', code)
  317.             
  318.             if status != 0:
  319.                 raise Exception('authentication failed. bad uname/pword?')
  320.             
  321.  
  322.         _recvauth = recver(_recvauth)
  323.         
  324.         def _sendproxysetup():
  325.             request = pack('!BBB', 5, 1, 0)
  326.             rresolve = False
  327.             
  328.             try:
  329.                 this.resolved_ip = socket.inet_aton(destaddr)
  330.             except socket.error:
  331.                 
  332.                 try:
  333.                     this.resolved_ip = socket.inet_aton(socket.gethostbyname(destaddr))
  334.                 this.resolved_ip = None
  335.                 rresolve = True
  336.  
  337.  
  338.             if rresolve:
  339.                 request += chr(3) + pstring(destaddr)
  340.             else:
  341.                 request += chr(1) + this.resolved_ip
  342.             request += pack('!H', destport)
  343.             return (request, 4)
  344.  
  345.         _sendproxysetup = (None, None, None, None, sender)(_sendproxysetup)
  346.         
  347.         def _recvproxysetup(data):
  348.             (five, null, _unused, status) = map(ord, data)
  349.             if five != 5:
  350.                 raise Exception('Was expecting 5, got: %r', five)
  351.             
  352.             if null != 0:
  353.                 raise Exception('Connection failed, reason code was: %r', null)
  354.             
  355.             if status in (1, 3):
  356.                 this.incoming_host_type = status
  357.                 return None
  358.             
  359.             raise Exception('Unknown error occurred.')
  360.  
  361.         _recvproxysetup = (recver,)(_recvproxysetup)
  362.         
  363.         def _sendpstringhost1():
  364.             return ('', 1)
  365.  
  366.         _sendpstringhost1 = sender(_sendpstringhost1)
  367.         
  368.         def _recvpstringhost1(data):
  369.             this.hostlen = ord(data)
  370.  
  371.         _recvpstringhost1 = (recver,)(_recvpstringhost1)
  372.         
  373.         def _sendpstringhost2():
  374.             return ('', this.hostlen)
  375.  
  376.         _sendpstringhost2 = (sender,)(_sendpstringhost2)
  377.         
  378.         def _recvpstringhost2(data):
  379.             this.boundhost = data
  380.  
  381.         _recvpstringhost2 = (recver,)(_recvpstringhost2)
  382.         
  383.         def _sendiphost():
  384.             return ('', 4)
  385.  
  386.         _sendiphost = sender(_sendiphost)
  387.         
  388.         def _recvhost(data):
  389.             this.boundhost = socket.inet_ntoa(data)
  390.  
  391.         _recvhost = (recver,)(_recvhost)
  392.         
  393.         def _getport():
  394.             return ('', 2)
  395.  
  396.         _getport = sender(_getport)
  397.         
  398.         def _recvport(data):
  399.             (this.boundport,) = unpack('!H', data)
  400.  
  401.         _recvport = (None, recver)(_recvport)
  402.         steps = ((_recvauthtype, _sendauthtype, None), (_recvauth, (_sendauth,), (lambda : this.authtype)), (_recvproxysetup, _sendproxysetup, None), (_recvhost, (_sendiphost,), (lambda : this.incoming_host_type == 1)), (_recvpstringhost1, (_sendpstringhost1,), (lambda : this.incoming_host_type == 3)), (_recvpstringhost2, (_sendpstringhost2,), (lambda : this.incoming_host_type == 3)), (_recvport, _getport, None))
  403.         for recvr, sendr, check in steps:
  404.             if check is None or check():
  405.                 yield sendr
  406.                 None(recvr)
  407.                 continue
  408.         
  409.         self._ProxySocket__proxysockname = (this.boundhost, this.boundport)
  410.         if this.resolved_ip is not None:
  411.             self._ProxySocket__proxypeername = (socket.inet_ntoa(this.resolved_ip), destport)
  412.         else:
  413.             self._ProxySocket__proxypeername = (destaddr, destport)
  414.         if not this.errors:
  415.             self._negotiation_done()
  416.         else:
  417.             self.close()
  418.  
  419.     
  420.     def _negotiatesocks5(self):
  421.         gen = self._negotiatesocks5_gen()
  422.         
  423.         def handler(data):
  424.             log.info('ProxySocket._negotiatesocks5: in =%r', data)
  425.             
  426.             try:
  427.                 next = gen.send(data)
  428.             except StopIteration:
  429.                 return None
  430.  
  431.             (data, term) = next()
  432.             if data and ord(data[0]) == 1:
  433.                 logdata = '<authstring omitted>'
  434.             else:
  435.                 logdata = data
  436.             log.info('ProxySocket._negotiatesocks5: out=%r, terminator=%r', logdata, term)
  437.             self.push(data)
  438.             self.push_handler(handler)
  439.             self.set_terminator(term)
  440.  
  441.         handler(None)
  442.  
  443.     
  444.     def __repr__(self):
  445.         parentrepr = asocket.__repr__(self).strip('<>')
  446.         return '<%s, fileno=%r>' % (parentrepr, self._fileno)
  447.  
  448.  
  449.  
  450. def main():
  451.     testapp = testapp
  452.     import tests.testapp
  453.     end = end
  454.     import AsyncoreThread
  455.     import wx as wx
  456.     a = testapp('../..')
  457.     a.toggle_crust()
  458.     
  459.     class HeadSocket(asocket):
  460.         
  461.         def __init__(self, *a, **k):
  462.             asocket.__init__(self, *a, **k)
  463.             self.set_terminator('\r\n\r\n')
  464.             self.push('HEAD / HTTP/1.0\r\n\r\n')
  465.             self.push_handler((lambda d: log.info(repr(d))))
  466.  
  467.         
  468.         def GetProxyInfo(self):
  469.             return { }
  470.  
  471.  
  472.     h = HeadSocket()
  473.     h.connect(('www.google.com', 80), success = (lambda s = h: log.info('success! socket: %r', s)))
  474.     a.MainLoop()
  475.     end()
  476.  
  477. if __name__ == '__main__':
  478.     
  479.     def GetProxyInfo():
  480.         return dict(proxytype = 3, username = 'digsby', password = 'password', addr = 'athena', port = 9999)
  481.  
  482.     print main()
  483.  
  484.